package com.gtt.jr.action;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import com.gtt.jr.action.base.BaseModelAction;
import com.gtt.jr.action.model.LoginModel;
import com.gtt.jr.repository.domain.User;
import com.gtt.jr.service.UserService;

public class LoginAdminAction extends BaseModelAction<LoginModel> {

	private static final long serialVersionUID = -4414762408059143491L;

	@Resource
	private UserService userService;

	@SuppressWarnings("unchecked")
	@Override
	public String execute() throws Exception {

		if (!checkValidation() || !checkUsernamePassword()) {
			getModel().setResult(false);
		} else {
			getSession().put("username", getModel().getUsername());
			getModel().setResult(true);
		}
		return JSON;
	}

	private boolean checkUsernamePassword() {
		User user = userService.load(getModel().getUsername());
		if (user == null) {
			getModel().setExist(false);
			return false;
		}
		getModel().setExist(true);
		return user.getPassword().equals(getModel().getPassword());
	}

	private boolean checkValidation() {
		return StringUtils.isNotEmpty(getModel().getUsername())
				&& StringUtils.isNotEmpty(getModel().getPassword());
	}

}
